<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="newName" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="newAge" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="newSex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addList">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="delBtn(index)">删除</button>
            <button @click="compile(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      newName: "",
      newAge: "",
      newSex: "男",
      num: "",
      flag: true,
      list: [
        { name: "Tom", age: 25, sex: "女" },
        { name: "Tom1", age: 23, sex: "男" },
      ],
    };
  },
  methods: {
    addList() {
      // 添加
      if (this.newName == "" || this.newAge < 0 || !this.newAge)
        return alert("请正确填写信息");

      if (this.flag) {
        this.list.push({
          name: this.newName,
          age: this.newAge,
          sex: this.newSex,
        });
      } else {
        this.list.splice(this.num, 1, {
          name: this.newName,
          age: this.newAge,
          sex: this.newSex,
        });
      }
      this.newName = "";
      this.newAge = "";
      this.newSex = "男";
      this.flag = true;
    },
    //删除
    delBtn(index) {
      this.list.splice(index, 1);
    },
    // 编辑
    compile(index) {
      this.newName = this.list[index].name;
      this.newAge = this.list[index].age;
      this.newSex = this.list[index].sex;
      // console.log(this.list[index]);
      this.flag = false;
      this.num = index;
    },
  },
};
</script>